package com.cm.stock.manager.dao;

import java.util.List;
import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;
import com.cm.stock.manager.dto.CommandeDTO;
import com.cm.stock.manager.dto.ClientDTO;


@Transactional
public class CommandeDAO {
	@PersistenceContext
	private EntityManager em;
	
	public CommandeDTO get(Integer id){
		return em.find(CommandeDTO.class, id);
	}
	
	public CommandeDTO save(CommandeDTO commande){
		em.persist(commande);
		return commande;
	}
	
	public CommandeDTO update(CommandeDTO commande){
		return em.merge(commande);
	}
	
	public CommandeDTO getByCode(String code){
		return (CommandeDTO) em.createQuery("select co from CommandeDTO co where co.code=:code")
				.setParameter("code", code)
				.getSingleResult();
	}
	
	public int getMaxId(){
		try{
			return (Integer) em.createQuery("select max(co.id) from CommandeDTO co ")
				.getSingleResult();
		}catch (Exception e) {
			return 0;
		}
		
	}
	@SuppressWarnings("unchecked")
	public List<CommandeDTO> getByClient(ClientDTO client){
		return  em.createQuery("select c from CommandeDTO c where c.client=:client")
				.setParameter("client", client)
				.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<CommandeDTO> getByDateEdition(Date dateedition){
		return  em.createQuery("select c from CommandeDTO c where c.dateEdition=:dateedition")
				.setParameter("dateedition", dateedition)
				.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<CommandeDTO> getByDateRendezVous(Date daterendezvous){
		return  em.createQuery("select c from CommandeDTO c where c.dateRendezvous=:daterendezvous")
				.setParameter("dateedition", daterendezvous)
				.getResultList();
	}
	
public void deleteOne(Integer id) throws Exception {
		
	CommandeDTO cm = em.find(CommandeDTO.class, id);
		if(cm==null){
			throw new Exception("commande inexistante!");
		}
		em.remove(cm);
	}

}
